package com.peanut.baby.mvp.msg;

import android.app.Activity;

import com.peanut.baby.InitManager;
import com.peanut.baby.http.BaseObserver;
import com.peanut.baby.http.BaseResponse;
import com.peanut.baby.http.BaseScheduler;
import com.peanut.baby.http.RetrofitClient;
import com.peanut.baby.model.AppMsg;
import com.peanut.baby.repository.MsgRepository;

import java.util.List;

import cn.nekocode.rxlifecycle.RxLifecycle;
import io.reactivex.Observable;

/**
 * Created by anonymouslystudio on 2017/8/25.
 */

public class MsgPresenter implements MsgContract.Presenter{
    private MsgContract.View view;
    Activity activity;
    public MsgPresenter(MsgContract.View view,Activity activity) {
        this.view = view;
        this.activity = activity;
    }

    @Override
    public void getMsgList(int pageNo, int pageSize) {
        Observable obs = RetrofitClient.getInstance().getPushMessages(InitManager.getInstance().getUserId(),
                pageNo,pageSize,InitManager.getInstance().getUser().userToken);
        obs.compose(BaseScheduler.<BaseResponse<List<AppMsg>>>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<List<AppMsg>>() {
            @Override
            protected void onHandleSuccess(List<AppMsg> o) {
                if(o != null && !o.isEmpty()){
                    for(int i=0;i<o.size();i++){
                        AppMsg msg = o.get(i);
                        msg.readFlag = MsgRepository.getInstance().hasReadedFlag(msg)? 1: 0;
                    }

                }
                view.onMsgGet(o);
            }

            @Override
            protected void onHandleError(String code,String msg) {
                view.onGetMsgFailed(msg);
            }

        });
    }

    @Override
    public void setMsgReaded(final AppMsg _msg) {
        MsgRepository.getInstance().updateReadedFlag(_msg);
        Observable obs = RetrofitClient.getInstance().setMessageReaded(_msg.id+"",InitManager.getInstance().getUser().userToken);
        obs.compose(BaseScheduler.<BaseResponse<String>>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<String>() {
            @Override
            protected void onHandleSuccess(String o) {
                MsgRepository.getInstance().updateReadedFlag(_msg);
            }

            @Override
            protected void onHandleError(String code,String msg) {
                MsgRepository.getInstance().updateReadedFlag(_msg);
            }

        });
    }
}
